package com.edu.zut.controller;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.zut.domain.RegisterVo;
import com.edu.zut.entity.User;
import com.edu.zut.result.HttpCode;
import com.edu.zut.result.ResponseResult;
import com.edu.zut.service.UserRoleService;
import com.edu.zut.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 许文科
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserRoleService userRoleService;

    @GetMapping("/test")
    @PreAuthorize("hasRole('student')")
    public ResponseResult show1() {
        return new ResponseResult("404", "测试成功", null);
    }

    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user) {
        return userService.login(user);
    }

    @PostMapping("/user/register")
    public ResponseResult register(@RequestBody RegisterVo registerVo) {
        return userService.register(registerVo);
    }

    @PostMapping("/user/findPassword")
    public ResponseResult findPassword(@RequestParam("userName") String userName,
                                       @RequestParam("userPhone") String userPhone,
                                       @RequestParam("newPassword") String newPassword) {
        return userService.findPassword(userName, userPhone, newPassword);
    }

    @GetMapping("/page")
    @PreAuthorize("hasAnyRole('teacher','admin')")
    public ResponseResult getStudentsList(@RequestParam("pageNum") Integer pageNum,
                                          @RequestParam("pageSize") Integer pageSize) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().orderByAsc("user_type");

        return new ResponseResult(HttpCode.SUCCESS, "成功", userService.page(new Page<User>(pageNum, pageSize), queryWrapper));
    }

    //新增
    @PostMapping("/user")
    @PreAuthorize("hasAnyRole('teacher','admin')")
    public ResponseResult addStudent(@RequestBody User user) {
        return userService.addStudent(user);
    }

    //编辑更新
    @PutMapping("/user")
    @PreAuthorize("hasAnyRole('teacher','admin')")
    public ResponseResult edit(@RequestBody User user) {
        return userService.edit(user);
    }

    @PutMapping("/{userId}/state/{status}")
    @PreAuthorize("hasAnyRole('teacher','admin')")
    public ResponseResult updateStatus(@PathVariable("userId") Long userId, @PathVariable("status") String status) {
        return userService.updateStatus(userId, status);
    }

    @PostMapping("/find")
    @PreAuthorize("hasAnyRole('teacher','admin')")
    public ResponseResult findUser(@RequestBody User user) {
        return userService.find(user);
    }

    @DeleteMapping("/deleteUser")
    @PreAuthorize("hasAnyRole('teacher','admin')")
    public ResponseResult deleteUser(@PathParam("userId") Long userId) {
        return userService.deleteUser(userId);
    }

    @DeleteMapping("/deleteUsers")
    @PreAuthorize("hasAnyRole('teacher','admin')")
    public ResponseResult deleteUsers(@PathParam("userId") Long userId) {
        return userService.deleteUsers(userId);
    }

    @PostMapping("/user/modify-password")
    @PreAuthorize("hasAnyRole('admin','teacher','student')")
    public ResponseResult modifyPassword(@PathParam("userId") Long userId,
                                         @PathParam("password") String password,
                                         @PathParam("newPassword") String newPassword) {

        return userService.modifyPassword(userId, password, newPassword);
    }

    @PostMapping(value = "/user/avatar")
    @PreAuthorize("hasAnyRole('admin','teacher','student')")
    public ResponseResult avatar(MultipartFile file) {

        return userService.avatar(file);
    }

    /**
     * 导出接口
     *
     * @param response
     * @throws Exception
     */
    @GetMapping("/user/export")
    @PreAuthorize("hasAnyRole('admin','teacher')")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查询出所有的数据
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_type", "1");
//        wrapper.eq("user_type", "2");
        List<User> userList = userService.list(wrapper);
        //在内存操作，写到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //一次性写出userList内的对象到excel，使用默认样式，强制输出标题
        writer.write(userList, true);

        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=uft-8");
        String fileName = URLEncoder.encode("User信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment,filename:" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }


    /**
     * 导入接口
     */
    @PostMapping("/user/import")
    @PreAuthorize("hasAnyRole('admin','teacher')")
    public ResponseResult imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        List<User> list = reader.readAll(User.class);
        for (User u : list) {
//            System.out.println(u);
            u.setPassword(passwordEncoder.encode(u.getPassword()));
            userService.save(u);
            //更新sys_user_role表
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("user_name", u.getUserName());
            User one = userService.getOne(wrapper);
            userRoleService.insertOne(one.getUserId());
        }
        //userService.saveBatch(list);
        return new ResponseResult(HttpCode.SUCCESS, "导入成功", null);

    }

    @GetMapping("/user/get-user-rate")
    @PreAuthorize("hasAnyRole('admin','teacher','student')")
    public ResponseResult getUserRate() {
        return userService.getUserRate();
    }

    @PostMapping("/user/info")
    @PreAuthorize("hasAnyRole('admin','teacher','student')")
    public ResponseResult info(@RequestParam("userName") String userName,
                               @RequestParam("userNumber") String userNumber,
                               @RequestParam("phoneNumber") String phoneNumber,
                               @RequestParam("sex") String sex) {
        return userService.info(userName, userNumber, phoneNumber, sex);
    }

}
